package code20_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test04_返回主键 {
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement ps = null;
		
		String sql = "insert into t_user (username,password,age) values ('qiaoqi','123',19)";
		
		try {
			conn = JdbcUtil.getConnection();
			
			// 传入常量值RETURN_GENERATED_KEYS，表示返回生成的主键
			ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
			ps.executeUpdate();
			
			// 执行完executeUpdate()后，可以获取生成的主键了
			ResultSet rs = ps.getGeneratedKeys(); // 返回一个结果集，可能是复合主键
			while(rs.next()){
				System.out.println(rs.getInt(1)); 
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JdbcUtil.close(conn, ps, null);
		}
	}
}
